package org.hot100_6.leetcode15;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static void main(String[] args) {

    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();

        int n = nums.length;

        Arrays.sort(nums);

        for (int curr = 0; curr < n; curr++) {
            if (nums[curr] > 0) {
                return list;
            }

            if (curr > 0 && nums[curr] == nums[curr - 1]) {
                continue;
            }
            int left = curr + 1;
            int right = n - 1;

            while (left < right) {
                int sum = nums[curr] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    List<Integer> item = new ArrayList<>();
                    item.add(nums[curr]);
                    item.add(nums[left]);
                    item.add(nums[right]);
                    list.add(item);

                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }

                    left++;
                    right--;
                }
            }
        }

        return list;
    }
}
